package cn.javase.concurrent._设计模式._异步模式之生产者消费者;

import java.util.LinkedList;
import lombok.extern.slf4j.Slf4j;

/**
 * 消息队列
 */
@Slf4j
public class MessageQueue {

    private LinkedList<Message> queue;
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
        queue = new LinkedList<>();
    }

    // 放入
    public void put(Message message) {
        synchronized (this) {
            while (queue.size() == capacity) {
                log.debug("消息队列满了...");
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            queue.addLast(message);
            this.notifyAll();
        }
    }

    // 拿取
    public Message take() {
        synchronized (this) {
            while (queue.isEmpty()) {
                log.debug("消息队列空了...");
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            Message message = queue.removeFirst();
            this.notifyAll();
            return message;
        }
    }

}
